class FollowHotPostSetting < ActiveRecord::Base
  
  belongs_to :hot_post, :counter_cache => :users_count
  belongs_to :read_lz_sub_hot_post, :class_name => "SubHotPost", :foreign_key => "read_lz_sub_hot_post_id"
  belongs_to :read_no_lz_sub_hot_post, :class_name => "SubHotPost", :foreign_key => "read_no_lz_sub_hot_post_id"
  belongs_to :user
  belongs_to :tool
  
  validates_uniqueness_of :hot_post_id, :scope => :user_id
  
  validates_presence_of :hot_post_id,
    :user_id,
    :tool_id
    
  validates_inclusion_of :scope, :in => %w(lz all)
    
  def after_initialize
    self.tool_id = Tool.find_by_code('zhui_tian_ya').id
  end
  
  def hot_post_updated?    
    if scope.lz?
      hot_post.the_last_lz_sub_hot_post && "#{Date.today} #{report_hour}:0:0".to_datetime.ago(1.days) <= hot_post.the_last_lz_sub_hot_post.released_at.to_s.to_datetime
    else
      hot_post.the_last_sub_hot_post && "#{Date.today} #{report_hour}:0:0".to_datetime.ago(1.days) <= hot_post.the_last_sub_hot_post.released_at.to_s.to_datetime
    end
  end
  
  def status
    ActiveSupport::StringInquirer.new(self[:status])
  end
    
  def scope
    ActiveSupport::StringInquirer.new(self[:scope])
  end
  
  def zhui!
    self.status = 'zhui'
    save false
  end
  
  def give_up!
    self.status = 'give_up'
    save false
  end
  
  def lz_show_status
    ActiveSupport::StringInquirer.new(self[:lz_show_status])
  end
  
  def allow_sms
    ActiveSupport::StringInquirer.new(self[:allow_sms])
  end
  
  def allow_email
    ActiveSupport::StringInquirer.new(self[:allow_email])
  end
  
  def hl_lz!
    self.lz_show_status = 'high_light'
    save false
  end
  
  def ll_lz!
    self.lz_show_status = 'low_light'
    save false
  end
  
  def read!(sub_hot_post)
    scope.lz? ? read_lz!(sub_hot_post) : read_no_lz!(sub_hot_post)
  end
  
  def read_sub_hot_post(args = { :scope => scope})
    (args[:scope] == 'lz' ? read_lz_sub_hot_post : read_no_lz_sub_hot_post) || hot_post.the_first_sub_hot_post
  end
  
  def scope!(new_scope)
    self.scope = new_scope      
    save!
  end
  
  def read_page(args = { })
    args[:scope] ||= scope
    count = args[:scope] == 'lz' ? (      
      read_lz_sub_hot_post_id.blank? ? (
        args[:per_page]
      ) : (
        SubHotPost.count( 
          :conditions => [
            'hot_post_id = ? and author = ? and id <= ?',
            hot_post.id,
            hot_post.author,
            read_lz_sub_hot_post_id
          ]
        )
      )
      
    ) : (
      read_no_lz_sub_hot_post_id.blank? ? (
        args[:per_page]
      ) : (
        SubHotPost.count( 
          :conditions => [
            'hot_post_id = ? and id <= ?',
            hot_post.id,
            read_no_lz_sub_hot_post_id
          ]
        )
      )      
    )
    (count % args[:per_page]) > 0 ? (count / args[:per_page] + 1) : ( (count / args[:per_page] > 0) ? (count / args[:per_page]) : (1))
  end
  
  def read_lz!(sub_hot_post)    
    self.read_lz_sub_hot_post = sub_hot_post
    self.read_lz_sub_hot_posts_count = SubHotPost.count(:conditions => [
      'hot_post_id = ? and id <= ? and author =? ',
      hot_post.id,
      sub_hot_post.id,
      hot_post.author
    ])
    save false
  end
  
  def read_no_lz!(sub_hot_post)
    self.read_no_lz_sub_hot_post = sub_hot_post
    self.read_no_lz_sub_hot_posts_count = SubHotPost.count(:conditions => [
      'hot_post_id = ? and id <= ? ',
      hot_post.id,
      sub_hot_post.id
    ])
    # 记录前一个楼主
    read_lz!(sub_hot_post.pre_neighbor_of_lz || sub_hot_post)
  end
  
  def read_schedule_ratio(args = { :scope => scope })
    #logger.debug "*****************#{hot_post.title}"
    args[:scope] == 'lz' ? (
      #logger.debug "========== read_lz_sub_hot_posts_count: #{read_lz_sub_hot_posts_count} == hot_post.lz_sub_hot_posts_count: #{hot_post.lz_sub_hot_posts_count}"
      format('%0.4f',(read_lz_sub_hot_posts_count * 1.0 / (hot_post.lz_sub_hot_posts_count == 0 ? 1 : hot_post.lz_sub_hot_posts_count))).to_f
    ) : (
      #logger.debug "========== read_no_lz_sub_hot_posts_count: #{read_no_lz_sub_hot_posts_count} == hot_post.sub_hot_posts_count: #{hot_post.sub_hot_posts_count}"
      format('%0.4f',(read_no_lz_sub_hot_posts_count * 1.0 / (hot_post.sub_hot_posts_count == 0 ? 1 : hot_post.sub_hot_posts_count))).to_f
    )
  end
  
  def read_schedule_percent(args = { :scope => scope })
    format('%0.2f',read_schedule_ratio(args) * 100)
  end

  def all_read?
    read_schedule_percent.to_i == 100
  end
  
  def setting
    UserToolSetting::ZhuiTianYa.find_by_user_id user.id
  end
  
  def send_sm
    if allow_sms.yes?
      raise '发送失败，您尚未绑定手机号。' if not user.mobile?
      Sm.create!( :user => user,
          :content => sm_conent ,
          :pri => 2)
      self.smed_at = Time.now
      save(false)
      user.add_sms_count!
      setting.add_sms_count!
    end
  end
  
  def sm_conent
    hot_post_updated? ? (
      "天涯社区的《#{hot_post.title}》#{scope.lz? ? "在最近的一天内楼主有更新，您才阅读了#{read_schedule_percent}%，赶快上去看看！！！" : "在最近的一天内有人跟帖，您才阅读了#{read_schedule_percent}%，，赶快上去看看！！！"}【麦吐司网】"
    ) : (
      "天涯社区的《#{hot_post.title}》#{scope.lz? ? "在最近的一天内楼主没有更新，您已阅读了#{read_schedule_percent}%，再等等吧！！！" : "在最近的一天内无人跟帖，您已阅读了#{read_schedule_percent}%，再等等吧！！！"}【麦吐司网】"
    )
  end
  
  def send_email
    if allow_email.yes?
      UserMailer.deliver_tian_ya_hot_post_daily_report :hot_post => hot_post,
        :user => user,
        :setting => self
      self.emailed_at = Time.now
      save(false)
      user.add_emails_count!
      setting.add_emails_count!
    end
  end
  
  def self.send_sms
    all(
      :conditions => [
        '        report_hour = ?
          and (Date(smed_at) < ?
            or (Date(smed_at) = ? and Hour(smed_at) < ? )
            or smed_at is null)
          and allow_sms = ? and status = ?',
        Time.now.hour,
        Date.today,
        Date.today,
        Time.now.hour,
        'yes',
        'zhui'
      ]
    ).each do |setting|
      setting.send_sm if not setting.hot_post.status.hidden?
    end
  end

  def self.send_emails
    email_settings = all(
      :conditions => [
        '        report_hour = ?
          and (Date(emailed_at) < ?
            or (Date(emailed_at) = ? and Hour(emailed_at) < ? )
            or emailed_at is null)
          and allow_sms = ? and status = ? ',
        Time.now.hour,
        Date.today,
        Date.today,
        Time.now.hour,
        'yes',
        'zhui'
      ],
      :order => 'rand()'
    )
    email_settings.each do |setting|
      setting.send_email if not setting.hot_post.status.hidden?
    end
  end
end
